<template>
  <div>
    <el-form :rules="loginRules" ref="loginForm" :model="loginForm" class="loginContainer">
      <h3 class="loginTitle">系统登录</h3>
      <el-form-item prop="username">
        <el-input type="text" auto-complete="false" v-model="loginForm.username" placeholder="请输入账号"></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input type="password" auto-complete="false" v-model="loginForm.password" placeholder="请输入账号"></el-input>
      </el-form-item>
      <el-form-item prop="code">
        <el-input type="text" auto-complete="false" v-model="loginForm.code" placeholder="点击获取" style="width: 250px;margin-right: 5px"></el-input>
        <img :src="captchaUrl" alt="" @click="updateImg">
      </el-form-item>
      <el-button type="primary" style="width: 100%" @click="login">登录</el-button>
    </el-form>

  </div>
</template>

<script>
export default {
  data () {
    return {
      captchaUrl: '/captcha?time='+ new Date(),
      // 登录表单
      loginForm: {
        username: 'admin',
        password: '123',
        code: ''
      },
      //校验登录表单
        loginRules:{
          username: [
            { required: true, message: "请输入用户名", trigger: "blur" },
            { min: 3, max: 10, message: '长度在 3 到 5 个字符', trigger: 'blur' }
          ],
          password: [
            { required: true, message: "请输入密码", trigger: "blur" },
            { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' } ],
          code: [
            { required: true, message: "请输入验证码", trigger: "blur" }
          ]
        }
    }
  },
  created () {
     
  },
  methods: {
    updateImg () {
      this.captchaUrl = '/captcha?time='+ new Date()
    },
    login () {
      this.$refs.loginForm.validate((valid) => {
        if(valid) {
          this.postRequest('/login', this.loginForm).then(resp => {
            console.log(resp)
            console.log(resp.data)
            if (resp) {
                //alert(JSON.stringify(resp));
                //存储用户token
                const tokenStr = resp.data.tokenHead + resp.data.token;
                window.sessionStorage.setItem('tokenStr', tokenStr);
                //页面跳转
                let path = this.$route.query.redirect;
                this.$router.replace((path == '/' || path == undefined) ? '/home' : path)
            } else {
            this.$message.error('请输入所有字段');
            return false;
          }
          })
        }
      })
    }
     
  }
}
</script>

<style>
  .loginContainer {
    border-radius: 15px;
    background-clip: padding-box;
    margin: 180px auto;
    width: 350px;
    padding: 15px 35px 15px 35px;
    background: #fff;
    border: 1px soild #eaeaea;
    box-shadow: 0 0 25px #cac6c6;
  }
  .loginTitle {
    margin: 0px auto 40px auto;
    text-align: center;
  }
  .el-form-item__content {
    display: flex;
    align-content: center;
  }
</style>
